package com.ticket.common.token;


import com.ticket.common.string.MD5;
import com.ticket.common.string.StringUtil;
import com.ticket.common.time.CommonFunction;

import java.util.Date;

public class TokenUtil {
    private static final String SALT = "yunhuan";
    private static SimpleScheduleConfig scheduleConfig = new SimpleScheduleConfig();

    public TokenUtil() {
    }

    public static String genToken(String userId) {
        return genToken(userId, (String)null);
    }

    public static String genToken(String id, String type) {
        MD5 md5 = new MD5();
        String time = scheduleConfig.currentTime;
        if ("last".equals(type)) {
            time = scheduleConfig.lastTime;
        }

        String key = id + "yunhuan" + time;
        System.out.println(CommonFunction.format(new Date(), "yyyyMMddHH")+scheduleConfig.salt);
        System.out.println("this is Key is this time and where boolean?:"+key);
        return md5.getMD5ofStr(key);
    }

    public static String genTokenByTime(String id, String time) {
        MD5 md5 = new MD5();
        String key = id + "yunhuan" + time;
        return md5.getMD5ofStr(key);
    }

    public static boolean checkToken(String id, String token) {   //微信小程序發送過來的
        System.out.println("id+md5():"+genToken(id,""));
        token = token.toUpperCase();
        if (StringUtil.isEmpty(token)) {
            return false;
        } else if (!token.equals(genToken(id, "current")) && !token.equals(genToken(id, "last"))) {
            return token.equals(genToken(id, CommonFunction.format(new Date(), "yyyyMMddHH") + scheduleConfig.salt));
        } else {
            return true;
        }
    }
}
